<script>
ids= new Array()
    </script>
<form id="form_facture" method="post" {{ form_enctype(form) }}>
    <div class="span12">
        <div class="box gradient">
            <div class="title" style="text-align: center">
                <h4>Facturation de 
                    
                {% for bonlivraison in bonslivraison %}
                    <script>
                    ids[ids.length]='{{bonlivraison.id}}'
                        </script>
                        {{bonlivraison.reference}}&nbsp;-&nbsp;
                        {% endfor %}
                        {% set bonlivraison = bonslivraison[0] %}
                </h4>
            </div>

            <div class="content noPad clearfix">
                <table style="width: 100%">
                    <tr>
                        <td style="width: 20%">
                            <label>Date:</label>
                            <div>
                                    {{ form_widget(form.date)}}{{ form_widget(form._token)}}
                                    <input id="now" type="text" style="width: 70px;" readonly/>
                                    <img src="/images/start.jpg" height="30" width="30" style="display: none;" id="start"> 
                                    <img src="/images/previous.jpg" height="30" width="30" style="display: none;" id="prev"> 
                                </div>
                            </td>
                            <td  style="width: 20%">
                                <label>Fournisseur:</label>
                                <div  style="width: 200px">
                                    <label>{{bonlivraison.fournisseur.raisonSocial}}</label>
                                    <input name="gds_achatbundle_facturefournisseurtype[fournisseur]" type="hidden" value="{{bonlivraison.fournisseur.id}}" />
                                </div> 
                            </td>
                            <td  style="width: 20%">
                                <label>Departement:</label>
                                <div style="width: 200px">
                                    {{ render(controller('GdsVenteBundle:Devis:getAllDepartement')) }}
                                    </div> 
                                </td>
                                <td  style="width: 40%">
                                    <label>Numero Facture:</label>
                                {{ form_widget(form.reference,{'attr':{'class':'span8 text','style':'width:200px'}})}}
                                </td>
                            </tr>
                        </table>

                    </div> 
                </div>
            </div>
        </form>

        <div class="span12" style="margin-left:0">

            <div class="box gradient">
                <div class="content noPad clearfix">
                    <table id="table_facture" cellpadding="0" cellspacing="0" border="0" class="responsive  display table table-bordered" width="100%">
                        <thead>
                            <tr >
                                <th>N°</th>
                                <th>Reference</th>
                                <th>Designation</th>
                                <th>Qte</th>
                                <th>P.U.HT</th>
                                <th>TVA</th>
                                <th>Remise</th>
                                <th>P.U.TTC</th>
                                <th id="th_total" style="width:10%">Total</th>
                            </tr>
                        </thead>
                        <tbody id="gds_achatbundle_lignebonlivraisonfournisseurtype">
                            {% set total_ttc = 0 %}
                                {% set l =0 %}
                                {% for bonlivraison in bonslivraison %}
                                <tr>
                                    <th colspan="9">Bon de Livraison : {{bonlivraison.reference}}</th>
                                </tr>
                            {% for ligne in bonlivraison.lignes %}
                                <tr class="ayo">
                                    <td>{{l}}</td>
                                    <td>{{ligne.article.reference}}</td>
                                    <td>{{ligne.article.designation}}</td>
                                    <td>{{ligne.quantite}}</td>
                                    <td>{{ligne.prixUnitaireHt}}</td>
                                    <td id="td_tva_{{l}}">{{ligne.tauxTva}}</td>
                                    <td>{{ligne.tauxRemise}}</td>
                                    {% set ttc = ligne.prixUnitaireHt*(1+ligne.tauxTva/100)*(1-ligne.tauxRemise/100) %}
                                    <td>{{ttc|number_format(3)}}</td>
                                    {% set total = ttc*ligne.quantite %}
                            {% set total_ttc = total+total_ttc %}
                                    <td id="td_total_{{l}}">{{total|number_format(3)}}</td>
                                    {% set l=l+1 %}
                                </tr>
                                {% endfor %}
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="span2" style="margin-left:83%">
                    <div class="content noPad clearfix">
                        <table cellpadding="0" cellspacing="0" border="1px" class="responsive  display table table-bordered" width="100%" style="border:#D0E9F5 ">
                            <thead>
                                <tr>
                                    <th colspan="2" class="center" style="text-align: center">TOTAL TTC</th>
                                    <th id="total_ttc" class="center">{{timbre|number_format(3)}}</th>
                                    <th id="total_ttc" class="center">{{total_ttc|number_format(3)}}</th>
                                    <th class="center">Total : {{(total_ttc+ timbre)|number_format(3)}}</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
    {# Ajout d'un lien pour ajouter un champ cat�gorie suppl�mentaire. #}
            <div class="span2" style="margin-left:0">
                <div class="box gradient">
                    <div class="content noPad clearfix">
                        <table id="taxe" cellpadding="0" cellspacing="0" border="0" class="responsive  display table table-bordered" width="100%">
                            <thead>
                                <tr>
                                    <th>Taxe</th>
                                    <th>Base</th>
                                    <th>Montant</th>
                                </tr>
                            </thead>
                            <tbody id="taxe_body">
                                <tr id="tr_taxe_18">
                                    <td id="taxe_18">18%</td>
                                    <td id="base_18">0.000</td>
                                    <td id="montant_taxe_18">0.000</td>
                                </tr>
                                <tr>
                                    <td>Totaux</td>
                                    <td></td>
                                    <td id="total_taxe">0.000</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="span2" style="margin-right: 0">
                <table>
                    <tr>
                        <td style="text-align: center">
                            <input type="button" style="width:100px" id="submit_form_facture" value="Enregistrer" class="nostyle btn btn-success btn-large" />
                        </td>
                        <td style="text-align: center">
                            <input type="button" style="width:100px" id="submit_form_facture_print" value="Imprimer" onclick="EnregistrerImprimer()" class="nostyle btn btn-success btn-large" />
                        </td>
                    </tr>
                    <tr>
                        <td style="height: 20px"></td>
                    </tr>
                    <tr>
                        <td>
                            <input id="retour2" style="width:100px" type="button" class="btn btn-info cut-icon-previous"  value="Retour" onclick="retourListeDevis2()">
                        </td>
                    </tr>
                </table>
            </div>
            <script>
                                   RefraichirTaxe()
                                    timbre='{{timbre}}'
                                function refraichir() {
                                    i = 1
                                    $('.numero_ligne').each(function() {
                                        $(this).html(i)
                                        i++
                                    })
                                }
                                function getArticle(id) {
                                    for (i = 0; i < articles.length; i++) {
                                        if (articles[i].id == id) {
                                            return articles[i]
                                        }
                                    }
                                    return null
                                }
                                function RefraichirTaxe() {
                                    var rowCount = $('#gds_achatbundle_lignebonlivraisonfournisseurtype tr[class="ayo"]').length
                                    var total_ttc = 0
                                    var taux_tva = new Array();
                                    var taxes = new Array();
                                    for (i = 0; i < rowCount; i++) {
                                        taxes[i] = new Array()
                                        taxes[i]['tva'] = 0
                                        taxes[i]['base'] = 0
                                        taxes[i]['montant'] = 0
                                    }
                                    var cmp = 0
                                    var i_refraich = 0
                                    while (cmp < rowCount) {
                                        if ($('#td_total_' + i_refraich).html() != null) {
                                            var tva = parseFloat($('#td_tva_' + i_refraich).html())
                                            if (parseFloat($('#td_total_' + i_refraich).html()) > 0) {
                                                j = $.inArray(tva, taux_tva)
                                                if (j == -1) {
                                                    taux_tva.push(tva)
                                                    j = $.inArray(tva, taux_tva)
                                                }
                                                ttc = parseFloat($('#td_total_' + i_refraich).html())
                                                total_ttc += ttc
                                                ht = ttc / (1 + tva / 100)
                                                montant = ht * tva / 100
                                                taxes[j]['tva'] = tva
                                                taxes[j]['base'] += ht
                                                taxes[j]['montant'] += montant
                                            }
                                            cmp++
                                        }
                                        i_refraich++
                                    }
                                    
                                    taxes = TriTab(taux_tva, taxes)
                                    $('#taxe_body tr').remove()
                                    var totaux = 0
                                    for (i = 0; i < taux_tva.length; i++) {
                                        tva = taxes[i]['tva'].toFixed(2)
                                        totaux += taxes[i]['montant']
                                        $('#taxe_body').append('<tr id="tr_taxe_' + tva + '"><td id="taxe_' + tva + '">' + tva + '%</td><td id="base_' + tva + '">' + taxes[i]['base'].toFixed(3) + '</td><td id="montant_taxe_' + tva + '">' + taxes[i]['montant'].toFixed(3) + '</td></tr>');
                                    }
                                    $('#taxe_body').append('<tr><td>Totaux</td><td></td><td id="total_taxe">' + totaux.toFixed(3) + '</td></tr>');

                                }
                                function doRemiseChange(i) {
                                    var article = getArticle($('#gds_achatbundle_' + i + '_article').val())
                                    article.remise = $('#gds_achatbundle_' + i + '_taux_remise').val()
                                    quantite = article.quantite;
                                    prix_achat_ht = article.prix_achat;
                                    tva = article.taux_tva;
                                    puttc = prix_achat_ht
                                    puttc *= (1 + tva / 100)
                                    puttc *= (1 - article.remise / 100)
                                    $('#td_prix_u_ttc_' + i).html(puttc.toFixed(3));
                                    total = puttc * quantite
                                    $('#td_total_' + i).html(total.toFixed(3));
                                }
                                function doRPrixUnitaireChange(i) {
                                    var article = getArticle($('#gds_achatbundle_' + i + '_article').val())
                                    article.prix_achat = $('#gds_achatbundle_' + i + '_prix_unitaire_ht').val()
                                    quantite = article.quantite;
                                    prix_achat_ht = article.prix_achat;
                                    tva = article.taux_tva;
                                    puttc = prix_achat_ht
                                    puttc *= (1 + tva / 100)
                                    puttc *= (1 - article.remise / 100)

                                    $('#td_prix_u_ttc_' + i).html(puttc.toFixed(3));
                                    total = puttc * quantite
                                    $('#td_total_' + i).html(total.toFixed(3));
                                }
                                function time() {
                                    var time = new Date($.now())
                                    h = time.getHours() // 0-24 format
                                    m = time.getMinutes()
                                    s = time.getSeconds()
                                    $('#heure').val(s + m * 60 + h * 3600)
                                    if (h < 10)
                                        h = '0' + h
                                    if (m < 10)
                                        m = '0' + m
                                    if (s < 10)
                                        s = '0' + s
                                    $('#now').val(h + ':' + m + ':' + s)
                                }
                                function Test(obj) {
                                    var data = obj.value;
                                    var d = data.substring(0, data.length - 1)
                                    var index_virgule = data.indexOf('.')
                                    if (index_virgule > 0)
                                        apres_virgule = data.substring(data.indexOf('.') + 1, data.length)
                                    if (!TestVerif(data) || apres_virgule.length > 3)
                                        obj.value = d
                                }
                                function TestVerif(decimal) {
                                    var entier = "0123456789"
                                    var virgule = false
                                    var first_number = false
                                    for (index_verif = 0; index_verif < decimal.length; index_verif++) {
                                        if (entier.indexOf(decimal[index_verif]) < 0) {
                                            if (decimal[index_verif] == '.' && first_number) {
                                                if (virgule)
                                                    return false
                                                else
                                                    virgule = true
                                            } else {
                                                return false
                                            }
                                        } else {
                                            first_number = true
                                        }
                                    }
                                    return true
                                }
                                function EnregistrerImprimer() {
                                    imprimer()
                                    Enregistrer()
                                }
                                function imprimer() {
                                    alert('impression')

                                }
                                function inverser(tab, i, j, tab2) {
                                    temp = tab[i];
                                    base = tab2[i]['base']
                                    montant = tab2[i]['montant']
                                    tva = tab2[i]['tva']
                                    tab[i] = tab[j];
                                    tab[j] = temp;
                                    tab2[i]['base'] = tab2[j]['base']
                                    tab2[j]['base'] = base
                                    tab2[i]['montant'] = tab2[j]['montant']
                                    tab2[j]['montant'] = montant
                                    tab2[i]['tva'] = tab2[j]['tva']
                                    tab2[j]['tva'] = tva
                                }
                                function TriTab(tab, tab2) {
                                    n = tab.length;
                                    continuer = true;
                                    i = 0;
                                    iter = 0;
                                    while (continuer) {
                                        iter++;
                                        continuer = false;
                                        for (i = 0; i < n - 1; i++) {
                                            if (Math.max(tab[i], tab[i + 1]) != tab[i + 1]) {
                                                inverser(tab, i, i + 1, tab2);
                                                continuer = true;
                                            }
                                        }
                                    }
                                    return tab2;
                                }
                </script>
                <style>
                        .red {
                            color: red;
                            font-size: 18px;
                        }
                        .green{
                            color : green;
                        }
                    </style>
                    <script type="text/javascript">


                        $(document).ready(function() {
                            $('#departement').val({{app.user.departement.id}})
                            $('#departement').attr('disabled', true);
                            $('#gds_achatbundle_facturefournisseurtype_date').datepicker();
                            $('#retour2').hide()
                            mdp = ""
                            var fullDate = new Date();
                            var twoDigitMonth = fullDate.getMonth()
                            twoDigitMonth++
                            twoDigitMonth += "";
                            if (twoDigitMonth.length == 1)
                                twoDigitMonth = "0" + twoDigitMonth;
                            var twoDigitDate = fullDate.getDate() + "";
                            if (twoDigitDate.length == 1)
                                twoDigitDate = "0" + twoDigitDate;
                            var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
                            $("#gds_achatbundle_facturefournisseurtype_date").val(currentDate)
                            setInterval(time, 1000);
                            $('#form_facture').validate();
                            $('#submit_form_facture').click(function() {
                                $('#gds_achatbundle_facturefournisseurtype_reference').focus()
                                if ($('#form_facture').valid()) {
                                    $.ajax({
                                        url: '{{path("gds_achat_bons_livraison_facturer")}}',
                                        type: "POST",
                                        datatype: 'json',
                                        data: $('#form_facture').serialize() +'&heure=' + $('#heure').val() + '&departement=' + $("#departement option:selected").text+'&ids='+JSON.stringify(ids),
                                        success: function(data) {
                                            if (data.success) {
                                                $.msgBox({
                                                    title: "Facture",
                                                    content: "Enregistrement Effectué avec succés",
                                                    type: "info",
                                                    buttons: [{value: "OK"}],
                                                    success: function(result) {
                                                        location.reload();
                                                    }
                                                });
                                            } else {
                                                $.msgBox({
                                                    title: "Facture",
                                                    content: "Erreur D'enregistrement",
                                                    type: "error",
                                                    buttons: [{value: "OK"}]
                                                });
                                            }
                                        },
                                        error: function(e) {
                                            $.msgBox({
                                                title: "Facture",
                                                content: "Erreur D'enregistrement",
                                                type: "error",
                                                buttons: [{value: "OK"}],
                                                success: function(result) {

                                                }
                                            });
                                        }
                                    })
                                }
                            })

                            Array.prototype.remove = function(v) {
                                this.splice(this.indexOf(v) == -1 ? this.length : this.indexOf(v), 1);
                            }
                            index = 0;
                            nb_article = 1;
                            // var index_array = Array();
                            articles = new Array();
                            // On r�cup�re la balise <div> en question qui contient l'attribut � data-prototype � qui nous int�resse
                            $container = $('#gds_achatbundle_lignebonlivraisonfournisseurtype');


                        });
                        $(document).ready(function() {
                            $('#show_article').click(function() {
                                art = ""
                                for (i = 0; i < articles.length; i++)
                                    alert(articles[i].id + "   " + articles[i].reference + "  " + articles[i].quantite + "  " + articles[i].remise)
                            })
                        })

                        </script>

                        <input type="hidden" id="heure"/>
                        <input type="button" value="article" id="show_article">